function normalizedM = swnormal(M)
% Normalize (sparse matrix)
% scripted by Sun Sibai
% 2015 Apr. 8
%   M_{jk} = M_{jk} / sqrt( max(M_{:k}) max(M_{j:}) )
  [id1,id2,val] = find(M); % retrieve all nonzero elements of sparse matrix M
  m = zeros(size(id1));
  for it = id1 % to calc max of sparse matrix column
    m(it) = max((id1==it).*val);
  end
  m = m + (m==0); % change 0/0=NaN into 0
  N = size(M,1);
  val = val./sqrt(m(id1).*m(id2));
  normalizedM = sparse(id1,id2,val);
end
